package com.atguigu.juc.day04.cf;

import com.atguigu.juc.day04.pool.Demo01MyPool;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

public class Demo11AnyOf {

    public static void main(String[] args) {
        ExecutorService executorService = Demo01MyPool.getExecutorService();

        CompletableFuture<String> future01 = CompletableFuture.supplyAsync(() -> {

            try {
                System.out.println(Thread.currentThread().getName() + " 开始睡觉。");
                TimeUnit.SECONDS.sleep(2);
                System.out.println(Thread.currentThread().getName() + " 结束睡觉。");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            return "task 01 result";
        }, executorService);

        CompletableFuture<String> future02 = CompletableFuture.supplyAsync(() -> {

            try {
                System.out.println(Thread.currentThread().getName() + " 开始睡觉。");
                TimeUnit.SECONDS.sleep(4);
                System.out.println(Thread.currentThread().getName() + " 结束睡觉。");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            return "task 02 result";
        }, executorService);

        CompletableFuture<String> future03 = CompletableFuture.supplyAsync(() -> {

            try {
                System.out.println(Thread.currentThread().getName() + " 开始睡觉。");
                TimeUnit.SECONDS.sleep(6);
                System.out.println(Thread.currentThread().getName() + " 结束睡觉。");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            return "task 03 result";
        }, executorService);

        // anyOf() 方法：汇总任务
        // 只要任何一个任务完成，即可触发 whenComplete() 事件
        CompletableFuture.anyOf(future01, future02, future03).whenComplete((taskResult, throwable) -> {
            // taskResult 的值就是那个完成的具体任务的结果
            System.out.println("whenComplete() taskResult = " + taskResult);
            System.out.println("whenComplete() throwable = " + throwable);
        });
    }

}
